<template>
  <div class="max-w-2xl mx-auto space-y-6">
    <!-- 测试完成界面 -->
    <Card v-if="state === 'complete'">
      <CardHeader class="text-center">
        <CardTitle class="flex items-center justify-center gap-2">
          <Trophy class="w-6 h-6 text-red-500" />
          {{ t("coordinationTest.results.title") }}
        </CardTitle>
      </CardHeader>
      <CardContent class="space-y-6">
        <div class="text-center space-y-4">
          <div class="text-6xl font-bold text-primary">
            {{ finalScore }}
          </div>
          <div :class="`text-xl font-semibold ${rating.color}`">
            {{ rating.text }}
          </div>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div class="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
            <div class="text-2xl font-bold text-green-600">{{ stats.hits }}</div>
            <div class="text-sm text-muted-foreground">{{ t("coordinationTest.results.hits") }}</div>
          </div>
          <div class="text-center p-4 bg-red-50 dark:bg-red-950 rounded-lg">
            <div class="text-2xl font-bold text-red-600">{{ stats.misses }}</div>
            <div class="text-sm text-muted-foreground">{{ t("coordinationTest.results.misses") }}</div>
          </div>
          <div class="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
            <div class="text-2xl font-bold text-blue-600">{{ Math.round(stats.hitRate) }}%</div>
            <div class="text-sm text-muted-foreground">{{ t("coordinationTest.results.hitRate") }}</div>
          </div>
          <div class="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg">
            <div class="text-2xl font-bold text-purple-600">{{ Math.round(stats.avgAccuracy) }}%</div>
            <div class="text-sm text-muted-foreground">{{ t("coordinationTest.results.avgAccuracy") }}</div>
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div class="text-center p-4 bg-muted rounded-lg">
            <div class="text-xl font-bold">{{ Math.round(stats.avgReactionTime) }}ms</div>
            <div class="text-sm text-muted-foreground">{{ t("coordinationTest.results.avgReactionTime") }}</div>
          </div>
          <div class="text-center p-4 bg-muted rounded-lg">
            <div class="text-xl font-bold">{{ stats.totalTargets }}</div>
            <div class="text-sm text-muted-foreground">{{ t("coordinationTest.results.totalTargets") }}</div>
          </div>
        </div>

        <div class="flex gap-4">
          <Button @click="resetTest" variant="outline" class="flex-1">
            <RotateCcw class="w-4 h-4 mr-2" />
            {{ t("coordinationTest.results.retest") }}
          </Button>
          <Button @click="handleComplete" class="flex-1">
            {{ t("coordinationTest.results.saveResult") }}
          </Button>
        </div>
      </CardContent>
    </Card>

    <!-- 测试进行中计时器 -->
    <Card v-if="state === 'testing'">
      <CardContent class="pt-6">
        <div class="flex justify-between items-center mb-4">
          <div class="flex items-center gap-4">
            <div class="flex items-center gap-2">
              <Timer class="w-4 h-4" />
              <span class="font-mono text-lg">{{ timeLeft }}s</span>
            </div>
            <Badge :variant="timeLeft > 20 ? 'secondary' : timeLeft > 10 ? 'default' : 'destructive'">
              {{ timeLeft > 20 ? t('coordinationTest.timeStatus.ample') : timeLeft > 10 ? t('coordinationTest.timeStatus.warning') : t('coordinationTest.timeStatus.urgent') }}
            </Badge>
          </div>
          <div class="flex items-center gap-4">
            <div class="text-sm text-green-600">
              <Target class="w-4 h-4 inline mr-1" />
              {{ hits.length }}
            </div>
            <div class="text-sm text-red-600">
              <Zap class="w-4 h-4 inline mr-1" />
              {{ misses }}
            </div>
            <div class="text-sm text-blue-600">
              <MousePointer class="w-4 h-4 inline mr-1" />
              {{ Math.round((hits.length / Math.max(hits.length + misses, 1)) * 100) }}%
            </div>
          </div>
        </div>
        <Progress :model-value="((testDuration - timeLeft) / testDuration) * 100" />
      </CardContent>
    </Card>

    <!-- 主测试卡片 -->
    <Card>
      <!-- 准备状态 -->
      <template v-if="state === 'ready'">
        <CardHeader class="text-center">
                    <CardTitle class="flex items-center justify-center gap-2">
            <Target class="w-6 h-6 text-red-500" />
            {{ t("coordinationTest.title") }}
          </CardTitle>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="text-center space-y-4">
            <p class="text-muted-foreground">
              {{ t("coordinationTest.description", { testDuration: testDuration }) }}
            </p>
            <div class="flex justify-center gap-4">
              <Badge variant="outline">
                <Timer class="w-3 h-3 mr-1" />
                {{ testDuration }} {{ t("coordinationTest.seconds") }}
              </Badge>
              <Badge variant="outline">
                <Target class="w-3 h-3 mr-1" />
                {{ t("coordinationTest.dynamicTarget") }}
              </Badge>
              <Badge variant="outline">
                <Zap class="w-3 h-3 mr-1" />
                {{ t("coordinationTest.speedAccuracyBalance") }}
              </Badge>
            </div>
          </div>
          <div class="text-center">
            <Button
              size="lg"
              @click="startTest"
              class="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
            >
              <Target class="w-5 h-5 mr-2" />
              {{ t("coordinationTest.startTest") }}
            </Button>
          </div>
        </CardContent>
      </template>

      <!-- 测试进行中 -->
      <template v-if="state === 'testing'">
        <CardContent class="p-0">
          <div
            ref="containerRef"
            class="relative w-full h-96 bg-gradient-to-br from-blue-50 to-purple-50 dark:from-blue-950 dark:to-purple-950 overflow-hidden cursor-crosshair"
            @mousemove="handleMouseMove"
          >
            <!-- 鼠标指针指示器 -->
            <div
              ref="pointerRef"
              class="absolute w-2 h-2 bg-red-500 rounded-full pointer-events-none z-10"
              style="left: 0px; top: 0px;"
            />

            <!-- 目标 -->
            <div
              v-for="target in targets"
              :key="target.id"
              :class="`absolute rounded-full cursor-pointer transition-all duration-200 ${
                target.hit
                  ? 'bg-green-500 scale-150'
                  : 'bg-red-500 hover:bg-red-600 hover:scale-110'
              }`"
              :style="{
                left: target.x - target.size / 2 + 'px',
                top: target.y - target.size / 2 + 'px',
                width: target.size + 'px',
                height: target.size + 'px',
                opacity: target.hit ? 0 : target.timeToLive / targetLifetime,
                transform: `scale(${target.hit ? 0 : 1})`,
                border: '3px solid white',
                boxShadow: '0 2px 8px rgba(0,0,0,0.2)'
              }"
              @click.stop="(e) => handleTargetClick(target, e)"
            >
              <!-- 中心点 -->
              <div
                class="absolute bg-white rounded-full"
                :style="{
                  width: target.size * 0.2 + 'px',
                  height: target.size * 0.2 + 'px',
                  left: '50%',
                  top: '50%',
                  transform: 'translate(-50%, -50%)'
                }"
              />
            </div>

            <div class="absolute top-4 left-4 right-4 text-center">
              <p class="text-sm text-muted-foreground bg-background/80 px-3 py-1 rounded">
                {{ t("coordinationTest.instructions.clickCenter") }}
              </p>
            </div>
          </div>

          <!-- 实时统计 -->
          <div class="p-4">
            <div class="grid grid-cols-4 gap-4">
              <div class="text-center p-3 bg-green-50 dark:bg-green-950 rounded-lg">
                <div class="text-lg font-bold text-green-600">{{ hits.length }}</div>
                <div class="text-xs text-muted-foreground">{{ t("coordinationTest.stats.hits") }}</div>
              </div>
              <div class="text-center p-3 bg-red-50 dark:bg-red-950 rounded-lg">
                <div class="text-lg font-bold text-red-600">{{ misses }}</div>
                <div class="text-xs text-muted-foreground">{{ t("coordinationTest.stats.misses") }}</div>
              </div>
              <div class="text-center p-3 bg-blue-50 dark:bg-blue-950 rounded-lg">
                <div class="text-lg font-bold text-blue-600">
                  {{ Math.round((hits.length / Math.max(hits.length + misses, 1)) * 100) }}%
                </div>
                <div class="text-xs text-muted-foreground">{{ t("coordinationTest.stats.hitRate") }}</div>
              </div>
              <div class="text-center p-3 bg-purple-50 dark:bg-purple-950 rounded-lg">
                <div class="text-lg font-bold text-purple-600">
                  {{ hits.length > 0 ? Math.round((hits.reduce((sum, hit) => sum + hit.accuracy, 0) / hits.length) * 100) : 0 }}%
                </div>
                <div class="text-xs text-muted-foreground">{{ t("coordinationTest.stats.accuracy") }}</div>
              </div>
            </div>
          </div>
        </CardContent>
      </template>
    </Card>

    <!-- 测试说明 -->
    <Card>
      <CardContent class="pt-6">
        <h3 class="font-semibold mb-2">{{ t("coordinationTest.instructions.title") }}</h3>
        <ul class="text-sm text-muted-foreground space-y-1">
          <li>{{ t("coordinationTest.instructions.item1", { testDuration: testDuration }) }}</li>
          <li>{{ t("coordinationTest.instructions.item2") }}</li>
          <li>{{ t("coordinationTest.instructions.item3") }}</li>
          <li>{{ t("coordinationTest.instructions.item4") }}</li>
          <li>{{ t("coordinationTest.instructions.item5") }}</li>
        </ul>
      </CardContent>
    </Card>
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
import { Target, Timer, Zap, RotateCcw, MousePointer, Trophy } from 'lucide-vue-next';

// 测试常量
const testDuration = 30 // 秒
const targetInterval = 1200 // 毫秒
const targetLifetime = 2000 // 毫秒
const minTargetSize = 30
const maxTargetSize = 80

// 状态
const state = ref('ready') // 'ready', 'testing', 'complete'
const targets = ref([])
const hits = ref([])
const misses = ref(0)
const timeLeft = ref(testDuration)
const gameInterval = ref(null)
const timerInterval = ref(null)
const containerRef = ref(null)
const pointerRef = ref(null) // Ref for the pointer element

// 使用普通JS对象以避免不必要的响应式更新
const mousePosition = { x: 0, y: 0 }
let animationFrameId = null

// 生成目标
const generateTarget = () => {
  if (!containerRef.value) return

  const rect = containerRef.value.getBoundingClientRect()
  const size = minTargetSize + Math.random() * (maxTargetSize - minTargetSize)
  const margin = size / 2 + 10

  const target = {
    id: Date.now() + Math.random(),
    x: margin + Math.random() * (rect.width - 2 * margin),
    y: margin + Math.random() * (rect.height - 2 * margin),
    size,
    timeToLive: targetLifetime,
    hit: false
  }

  targets.value.push(target)

  // 目标生命周期结束后移除
  setTimeout(() => {
    targets.value = targets.value.filter(t => t.id !== target.id)
    if (!target.hit) {
      misses.value++
    }
  }, targetLifetime)
}

// 开始测试
const startTest = () => {
  state.value = 'testing'
  timeLeft.value = testDuration
  targets.value = []
  hits.value = []
  misses.value = 0

  // 计时器
  const timer = setInterval(() => {
    timeLeft.value--
    if (timeLeft.value <= 0) {
      clearInterval(timer)
      state.value = 'complete'
      timeLeft.value = 0
    }
  }, 1000)
  timerInterval.value = timer

  // 生成目标
  const game = setInterval(generateTarget, targetInterval)
  gameInterval.value = game

  // 立即生成第一个目标
  setTimeout(generateTarget, 500)
}

// 点击目标
const handleTargetClick = (target, event) => {
  if (target.hit) return

  event.stopPropagation()

  const rect = event.currentTarget.getBoundingClientRect()
  const centerX = rect.left + rect.width / 2
  const centerY = rect.top + rect.height / 2
  const clickX = event.clientX
  const clickY = event.clientY

  const distance = Math.sqrt(
    Math.pow(clickX - centerX, 2) + Math.pow(clickY - centerY, 2)
  )

  const accuracy = Math.max(0, 1 - (distance / (target.size / 2)))
  const hitTime = targetLifetime - target.timeToLive

  const hitResult = {
    accuracy,
    time: hitTime,
    size: target.size
  }

  hits.value.push(hitResult)
  target.hit = true
  target.clickTime = Date.now()

  // 短暂延迟后移除命中目标
  setTimeout(() => {
    targets.value = targets.value.filter(t => t.id !== target.id)
  }, 100)
}

// 鼠标移动
const handleMouseMove = (event) => {
  if (!containerRef.value) return

  const rect = containerRef.value.getBoundingClientRect()
  mousePosition.x = event.clientX - rect.left
  mousePosition.y = event.clientY - rect.top
}

// 重置测试
const resetTest = () => {
  state.value = 'ready'
  timeLeft.value = testDuration
  targets.value = []
  hits.value = []
  misses.value = 0

  if (gameInterval.value) clearInterval(gameInterval.value)
  if (timerInterval.value) clearInterval(timerInterval.value)
  gameInterval.value = null
  timerInterval.value = null
}

// 计算统计信息
const stats = computed(() => {
  const totalTargets = hits.value.length + misses.value
  const hitRate = totalTargets > 0 ? (hits.value.length / totalTargets) * 100 : 0
  const avgAccuracy = hits.value.length > 0 ? hits.value.reduce((sum, hit) => sum + hit.accuracy, 0) / hits.value.length : 0
  const avgReactionTime = hits.value.length > 0 ? hits.value.reduce((sum, hit) => sum + hit.time, 0) / hits.value.length : 0

  return {
    totalTargets,
    hits: hits.value.length,
    misses: misses.value,
    hitRate,
    avgAccuracy: avgAccuracy * 100,
    avgReactionTime: avgReactionTime
  }
})

// 计算最终得分
const finalScore = computed(() => {
  const statsValue = stats.value

  // 基础得分来自命中率
  let score = statsValue.hitRate

  // 精度加成
  score += statsValue.avgAccuracy * 0.3

  // 速度加成 (反应越快得分越高)
  const speedBonus = Math.max(0, (2000 - statsValue.avgReactionTime) / 2000) * 20
  score += speedBonus

  // 数量加成
  const volumeBonus = Math.min(statsValue.hits / 15, 1) * 10
  score += volumeBonus

  return Math.min(100, Math.max(0, Math.round(score)))
})

// 获取评级
const rating = computed(() => {
  const score = finalScore.value
  if (score >= 90) return { text: t('coordinationTest.rating.sharpshooter'), color: 'text-yellow-500' }
  if (score >= 80) return { text: t('coordinationTest.rating.excellent'), color: 'text-green-500' }
  if (score >= 70) return { text: t('coordinationTest.rating.good'), color: 'text-blue-500' }
  if (score >= 60) return { text: t('coordinationTest.rating.average'), color: 'text-gray-500' }
  return { text: t('coordinationTest.rating.needsPractice'), color: 'text-orange-500' }
})

// 完成测试
const handleComplete = () => {
  const statsValue = stats.value
  const result = {
    testType: t('coordinationTest.testType'),
    score: finalScore.value,
    details: t('coordinationTest.results.details', {
      hitRate: Math.round(statsValue.hitRate),
      avgAccuracy: Math.round(statsValue.avgAccuracy),
      avgReactionTime: Math.round(statsValue.avgReactionTime)
    }),
    timestamp: new Date()
  }
  emit('complete', result)
}

// 更新目标剩余时间
const updateInterval = ref(null)
watch(() => state.value, (newVal) => {
  if (newVal === 'testing') {
    updateInterval.value = setInterval(() => {
      targets.value = targets.value.map(target => ({
        ...target,
        timeToLive: Math.max(0, target.timeToLive - 50)
      }))
    }, 50)
  } else {
    if (updateInterval.value) clearInterval(updateInterval.value)
  }
})

// 动画循环，用于平滑指针移动
const updatePointer = () => {
  if (pointerRef.value) {
    pointerRef.value.style.transform = `translate3d(${mousePosition.x - 4}px, ${mousePosition.y - 4}px, 0)`
  }
  animationFrameId = requestAnimationFrame(updatePointer)
}

// 组件挂载和卸载时启动/停止动画循环
onMounted(() => {
  animationFrameId = requestAnimationFrame(updatePointer)
})

onUnmounted(() => {
  if (gameInterval.value) clearInterval(gameInterval.value)
  if (timerInterval.value) clearInterval(timerInterval.value)
  if (updateInterval.value) clearInterval(updateInterval.value)
  if (animationFrameId) cancelAnimationFrame(animationFrameId)
})

// 定义emit
const emit = defineEmits(['complete'])
</script>